package cn.kailangtu.dataspot.security;

import android.content.ComponentName;
import android.content.Intent;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

// 监控进程中的 ANR 检测（需 READ_LOGS 权限）
public class ANRMonitor {
    public void startMonitoring() {
        new Thread(() -> {
            Process process = null;
            try {
                process = Runtime.getRuntime().exec("logcat -b events");
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    if (line.contains("am_anr")) {
                        // 检测到 ANR 后重启主应用
                        restartMainApp();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private void restartMainApp() {
        Intent launch = new Intent();
        launch.setComponent(new ComponentName("cn.kailangtu.dataspot", "cn.kailangtu.dataspot.activify.SplashActivity"));
        launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //startActivity(launch);
    }
}
